package com.kayt.cyberBar.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密解密
 * @ClassName: SecurityUtil.java 
 * @author zhuyong
 * @CeateDate 2016年1月25日 上午10:24:46
 * @Description <p></p>
 *
 */
public class SecurityUtil {
	
	public final static String MD5 = "md5";
	public final static String MD2 = "md2";
	public final static String SHA_1 = "SHA-1";
	public final static String SHA1 = "SHA1";
	public final static String SHA_256 = "SHA-256";
	public final static String SHA_384 = "SHA-384";
	public final static String SHA_512 = "SHA-512";
	

	public static String getHexString(byte[] b) {
		if (b == null)
			return null;
		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; ++n) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			if (stmp.length() == 1)
				hs.append("0" + stmp);
			else
				hs.append(stmp);
		}
		return hs.toString();
	}

	/**
	 * 单向信息加密(信息摘要)，支持：md5、md2、SHA(SHA-1，SHA1)、SHA-256、SHA-384、SHA-512, <br>
	 * 返回值：String 加密后的密文 <br>
	 * @param bytes 传入加密字符串(明文) <br>
	 * @param method 指定算法(md5、md2、SHA(SHA-1，SHA1)、SHA-256、SHA-384、SHA-512) <br>
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	public static String ecodingPasswd(byte[] bytes, String method) throws NoSuchAlgorithmException {
		// 信息摘要算法
		MessageDigest md;
		md = MessageDigest.getInstance(method);
		md.update(bytes);
		// 使用base64进行编码，一避免出现丢数据情景
		return getHexString(md.digest());
	}
	
	public static String toMD5(String str, String encode) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		byte[] src;
			src = str.getBytes(encode);
		return ecodingPasswd(src,MD5);
	}
	
	public static String toMD5(String str) throws UnsupportedEncodingException, NoSuchAlgorithmException{
		return toMD5(str,"UTF-8");
	}
	


}
